const fs = require('fs')
const path = require('path')

class JsonFileCollectorPlugin {
  constructor(options) {
    this.options = {
      output: 'json-routes.json', // 输出文件名
      inputDir: 'src/assets/dist_data', // 输入文件夹路径
      ...options
    }
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync(
      'JsonFileCollectorPlugin',
      (compilation, callback) => {
        const { output, inputDir } = this.options
        const jsonFiles = {}
        const basePath = compiler.options.context
        const dirPath = path.resolve(basePath, inputDir)

        if (fs.existsSync(dirPath)) {
          this.collectJsonFilesRecursively(dirPath, jsonFiles)
        }

        const jsonString = JSON.stringify(jsonFiles, null, 2)
        compilation.assets[output] = {
          source: () => jsonString,
          size: () => Buffer.byteLength(jsonString)
        }

        callback()
      }
    )
  }

  collectJsonFilesRecursively(dirPath, jsonFiles) {
    const files = fs.readdirSync(dirPath)
    files.forEach(file => {
      const filePath = path.resolve(dirPath, file)
      const stat = fs.statSync(filePath)
      if (stat.isDirectory()) {
        // 如果是目录，则递归调用
        this.collectJsonFilesRecursively(filePath, jsonFiles)
      } else if (file.endsWith('.json')) {
        // 如果是 JSON 文件，则读取内容
        const relativePath = path.relative(
          path.dirname(this.options.inputDir),
          filePath
        )
        const routePath = relativePath
          .replace(/\\/g, '/')
          .replace(/\.json$/, '') // 构建类似于路由的路径
        const content = fs.readFileSync(filePath, 'utf8')
        jsonFiles[routePath] = JSON.parse(content)
      }
    })
  }
}

module.exports = JsonFileCollectorPlugin
